package com.example.ssoapp1.config;

import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * WebMvcConfig
 *
 * @author majun
 * @description WebMvcConfig
 * @date 2021/9/7
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public RestTemplate restOperations() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory()  {
            @Override
            protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
                try {
                    if (!(connection instanceof HttpsURLConnection)) {// http协议
                        //throw new RuntimeException("An instance of HttpsURLConnection is expected");
                        super.prepareConnection(connection, httpMethod);
                    }
                    if (connection instanceof HttpsURLConnection) {// https协议，修改协议版本
                        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                        // 信任任何链接
                        TrustStrategy anyTrustStrategy = (x509Certificates, s) -> true;
                        SSLContext ctx = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();
                        ((HttpsURLConnection) connection).setSSLSocketFactory(ctx.getSocketFactory());
                        ((HttpsURLConnection) connection).setHostnameVerifier((hostname, sslSession) -> true);
                        HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
                        super.prepareConnection(httpsConnection, httpMethod);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.prepareConnection(connection, httpMethod);
            }
        };


        requestFactory.setReadTimeout(5000);
        requestFactory.setConnectTimeout(5000);

        return new RestTemplate(requestFactory);
    }
}
